package com.isunland.managesystem.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.WorkProcessAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ProcessContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WorkProcess;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

public class WorkProcessListFragment extends BaseListFragment
    implements WorkProcessAdapter.Callback {

  protected static final int REQUEST_FINISH = 1;//已完成任务的时候刷新列表
  protected static final int REQUEST_ADD = 0;//添加成功的时候刷新列表

  private ArrayList<ProcessContent> mProcessContent;
  private WorkProcessAdapter mWorkProcessAdapter;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    final FloatingActionMenu mFamMenu = getFamMenu();
    mFamMenu.setVisibility(View.VISIBLE);
    FloatingActionButton mFabTemp =
        getFloatingActionButton("新增日计划", R.drawable.ic_assignment_turned_in,
            R.color.yelloy_textColor);
    FloatingActionButton mFabWeek =
        getFloatingActionButton("新增周计划", R.drawable.ic_assignment_turned_in, R.color.primary);

    mFamMenu.addMenuButton(mFabTemp);
    mFamMenu.addMenuButton(mFabWeek);
    mFabTemp.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        Intent intent = new Intent(getActivity(), TemproryplanActivity.class);
        mActivity.startActivityForResult(intent, REQUEST_ADD);
        mFamMenu.close(true);
      }
    });
    mFabWeek.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        Intent intent = new Intent(getActivity(), WeekPlanActivity.class);
        mActivity.startActivityForResult(intent, REQUEST_ADD);
        mFamMenu.close(true);
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_MY_PLAN;
  }

  @Override public void resolveResponse(String json) {
    WorkProcess process = new Gson().fromJson(json, WorkProcess.class);
    List<ProcessContent> content = process.getDataList();
    setAdapter(content);
  }

  private void setAdapter(List<ProcessContent> content) {
    if (mProcessContent == null) {
      mProcessContent = new ArrayList<>();
    }
    if (isPaging() && getCurrentPage() == 1) {
      mProcessContent.clear();
    }
    mProcessContent.addAll(content);
    if (mWorkProcessAdapter == null) {
      mWorkProcessAdapter = new WorkProcessAdapter(mActivity, mProcessContent, this);
      setListAdapter(mWorkProcessAdapter);
    }

    ((WorkProcessAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(final ListView l, View v, final int position, long id) {

    Intent intent = new Intent(getActivity(), WorkProcessEditActivity.class);
    ProcessContent item = mWorkProcessAdapter.getItem(position - 1);
    intent.putExtra(WorkProcessEditFragment.EXTRA_PROCESS_CONTENT, item);
    //intent.putExtra(WorkProcessDetailListFragment.EXTRA_ITEM, item != null ? item.getId() : null);
    mActivity.startActivityForResult(intent, REQUEST_FINISH);
    super.onListItemClick(l, v, position, id);
  }

  //填充添加按钮
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    //MenuInflater menuInflater = new MenuInflater(getActivity());
    inflater.inflate(R.menu.menu_add_plan, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      case R.id.menu_item_add_dayPlan:
        intent = new Intent(getActivity(), TemproryplanActivity.class);

        mActivity.startActivityForResult(intent, REQUEST_ADD);
        break;
      case R.id.menu_item_add_weekPlan:
        intent = new Intent(getActivity(), WeekPlanActivity.class);
        mActivity.startActivityForResult(intent, REQUEST_ADD);
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void delete(final ProcessContent item) {
    if (item == null) return;
    if (!"Temp".equalsIgnoreCase(item.getPlanKindTypeCode())) {
      ToastUtil.show("只能删除临时计划!");
      return;
    }

    if ("archive".equalsIgnoreCase(item.getEvaStatus()) || "eval".equalsIgnoreCase(
        item.getEvaStatus())) {
      ToastUtil.show("已评价或归档内容不允许删除!");
      return;
    }
    if (!MyStringUtil.equalsIgnoreCase(CurrentUser.newInstance(mActivity).getJobNumber(),
        item.getRegStaffId())) {
      ToastUtil.show("只能删除自己登记的任务!");
      return;
    }

    new AlertDialog.Builder(mActivity).setTitle("提示")
        .setMessage(R.string.deleteConfirm)
        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            volleyPostDelete(item);
          }
        })
        .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {

          }
        })
        .create()
        .show();
  }

  @Override public void convert(ProcessContent item) {
    if (item == null) return;
    Intent intent = new Intent(getActivity(), WorkprocessConvertActicity.class);
    intent.putExtra(WorkprocessConvertFragment.EXTRA_VALUE, item);
    startActivityForResult(intent, REQUEST_FINISH);
  }

  @Override public void distribute(ProcessContent item) {
    if (item == null) return;
    Intent intent = new Intent(getActivity(), WorkDistributeListActivity.class);
    intent.putExtra(WorkDistributeListFragment.EXTRA_CONTENT, item);
    startActivityForResult(intent, REQUEST_FINISH);
  }

  //	@Override
  //	public void onActivityResult(int requestCode, int resultCode, Intent data) {
  //		if (resultCode != Activity.RESULT_OK) {
  //			return;
  //		}
  //        if (REQUEST_FINISH==requestCode ||REQUEST_ADD==requestCode){
  //            volleyPost();
  //        }
  //
  ////		switch (requestCode) {
  ////		case REQUEST_FINISH:
  ////			volleyPost();
  ////			((WorkProcessListActivity)getActivity()).mFinishListFragment.volleyPost();
  ////			break;
  ////		case REQUEST_ADD:
  ////			volleyPost();
  ////			((WorkProcessListActivity)getActivity()).mFinishListFragment.volleyPost();
  ////			break;
  ////		default:
  ////			break;
  ////		}
  //
  //		super.onActivityResult(requestCode, resultCode, data);
  //	}

  /**
   * 删除临时计划
   */
  private void volleyPostDelete(ProcessContent item) {
    if (item == null) return;
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEMPLAN_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", item.getId());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess;
        try {
          MyUtils.dismissDialog();
          workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == workProcess || null == workProcess.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = workProcess.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            volleyPost();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.deleteFail, Toast.LENGTH_SHORT).show();
      }
    });
  }

  @Override public void initData() {
    super.initData();
    setIsPaging(true);
  }
}
